# -*- coding: utf-8 -*-
import configparser
import uuid
from datetime import datetime

import oss2
import requests
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice
import os
import logging
import time
import random

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 读取配置文件
config = configparser.ConfigParser()
# 假设config.ini位于脚本同级目录下
config.read('config.ini')

# 从配置文件中获取Access Key ID和Access Key Secret
access_key_id = config.get('configName', 'alibaba_cloud_access_key_id')
access_key_secret = config.get('configName', 'alibaba_cloud_access_key_secret')

# 使用获取的RAM用户的访问密钥配置访问凭证
auth = oss2.AuthV4(access_key_id, access_key_secret)

# 设置Endpoint和Region
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"

def get_jx3_bucket():
    return  oss2.Bucket(auth, endpoint, 'jx3-waiguan', region=region)

def create_bucket(bucket_name):
    try:
        # yourBucketName填写存储空间名称。
        bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
        bucket.create_bucket()
        logging.info("Bucket created successfully")
        return bucket
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to create bucket: {e}")


def upload_file_stream(bucket, object_name, data):
    try:
        input_data = requests.get(data)
        file_name = data.split('/')[-1]
        result = bucket.put_object(object_name, input_data)
        logging.info(f"File uploaded successfully, status code: {result.status}")
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to upload file: {e}")

"""
本地上传
"""
def upload_file_local(bucket, path):
    try:
        with open(path, 'rb') as file_obj:
            file_name=os.path.basename(path)
            # 根据日期+ uuid + file_name生成文件名
            object_name = f"{datetime.now().strftime('%Y-%m-%d')}/{uuid.uuid4().hex}/{file_name}"
            result = bucket.put_object(object_name,file_obj)
            if result.status == 200:
                logging.info(f"File uploaded successfully, url: {result.resp.response.url}")
                return result.resp.response.url
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to upload file: {e}")


def download_file(bucket, object_name):
    try:
        file_obj = bucket.get_object(object_name)
        content = file_obj.read().decode('utf-8')
        logging.info("File content:")
        logging.info(content)
        return content
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to download file: {e}")


def list_objects(bucket):
    try:
        objects = list(islice(oss2.ObjectIterator(bucket), 10))
        for obj in objects:
            logging.info(obj.key)
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to list objects: {e}")


def delete_objects(bucket):
    try:
        objects = list(islice(oss2.ObjectIterator(bucket), 100))
        if objects:
            for obj in objects:
                bucket.delete_object(obj.key)
                logging.info(f"Deleted object: {obj.key}")
        else:
            logging.info("No objects to delete")
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to delete objects: {e}")


def delete_bucket(bucket):
    try:
        bucket.delete_bucket()
        logging.info("Bucket deleted successfully")
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to delete bucket: {e}")


# 主流程
if __name__ == '__main__':
    # 1. 创建Bucket
    # bucket = create_bucket('jx3-waiguan')
    bucket = get_jx3_bucket()
    # 2. 上传文件
    # upload_file_stream(bucket, 'aaaaa', 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132')
    upload_file_local(bucket,'C:\\Users\\Administrator\\Pictures\\chikend.webp')
    # # 3. 下载文件
    # download_file(bucket, 'test-string-file')
    # # 4. 列出Bucket中的对象
    # list_objects(bucket)
    # # 5. 删除Bucket中的对象
    # delete_objects(bucket)
    # # 6. 删除Bucket
    # delete_bucket(bucket)
